package cn.edu.cdp.dumpling.controller;

import cn.edu.cdp.dumpling.entity.OrderList;
import cn.edu.cdp.dumpling.entity.ShoppingCart;
import cn.edu.cdp.dumpling.service.ShoppingCartService;
import cn.edu.cdp.dumpling.util.R;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
//@CrossOrigin
@RequestMapping("/shopping_carts")
public class ShoppingCartController {

    private final ShoppingCartService shoppingCartService;

    public ShoppingCartController(ShoppingCartService shoppingCartService) {
        this.shoppingCartService = shoppingCartService;
    }

    @PostMapping("/submit")
    public R submit(@RequestBody OrderList orderList) {
        if (shoppingCartService.submit(orderList)) {
            return R.success("提交订单成功", null);
        } else {
            return R.error("提交订单失败");
        }
    }

    // 查看
    @GetMapping
    public R list(@RequestParam("consumer_id") Integer consumerId) {
        List<ShoppingCart> list;
        if (consumerId != null) {
            LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ShoppingCart::getConsumerId, consumerId);
            list = shoppingCartService.list(wrapper);
        } else {
            return R.error("用户没有登录");
        }
        if (list == null || list.isEmpty())
            return R.error("查询失败");
        else
            return R.success("查询成功", list);
    }

    // 增加
    @PostMapping
    public R save(@RequestBody ShoppingCart shoppingCart) {
        if (shoppingCartService.save(shoppingCart))
            return R.success("添加成功", null);
        else
            return R.error("添加失败");
    }

    // 删除
    @DeleteMapping("{id}")
    public R removeById(@PathVariable Integer id) {
        if (shoppingCartService.removeById(id))
            return R.success("删除成功", null);
        else
            return R.error("删除失败");
    }

    // 修改购物车
    @PutMapping
    public R updateById(@RequestBody ShoppingCart shoppingCart) {
        if (shoppingCartService.updateById(shoppingCart))
            return R.success("修改成功", null);
        else
            return R.error("修改失败");
    }
}
